<script type="text/ecmascript-6">
    /**
     * Created by wcz on 2017/3/27.
     */
    export default {
        data () {
            const validatePhone = (rule, value, cb) => {
                let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

                if (!reg.test(value)) {
                    cb(new Error('请输入正确手机号'));
                } else {
                    cb()
                }
            }
            return {
                loading: false,
                currentPage: 1,
                total: 100,
                pageSize: 50,
                self: this,
                pointPersonId: -1,
                columns: [
                    {
                        title: '姓名',
                        key: 'name',
                        render (row, column, index) {
                            return `<Icon type="person"></Icon> <strong>${row.name}</strong>`;
                        }
                    },
                    {
                        title: '账户',
                        key: 'phone'
                    },
                    {
                        title: '密码',
                        key: 'password'
                    },
                    {
                        title: '联系方式',
                        key: 'way',
                        width: 250,
                        render (row, column, index) {
                            return `<p>电话：${row.phone}</p><p>邮箱：${row.email}</p>`;
                        }
                    },
                    {
                        title: '备注',
                        key: 'remark'
                    },
                    {
                        title: '...',
                        key: 'action',
                        width: 250,
                        align: 'center',
                        render (row, column, index) {
                            return `<i-button type="primary"  @click="edit(${index})">修改</i-button>`;
                        }
                    }
                ],
                list: [
                    {
                        id: 1,
                        type: 0,
                        name: '王小明',
                        phone: 13199992222,
                        email: '333333444444@qq.com',
                        remark: '北京市朝阳区芍药居',
                        password: '123456',
                    },
                ],
                form: {
                    type: '0',
                    name: '',
                    phone: '',
                    email: '',
                    remark: '',
                },
                rules: {
                    name: [
                        {required: true, message: '请填写名字', trigger: 'blur'},
                    ],
                    phone: [
                        {required: true, message: '请填写11位正确手机号', trigger: 'change'},
                        {validator: validatePhone, trigger: 'change'}
                    ],
                    email: [
                        {required: true, message: '请填写正确邮箱', trigger: 'change'},
                        {type: 'email', message: '请填写正确邮箱', trigger: 'change'},
                    ],
                    password: [
                        {required: true, message: '请填写密码', trigger: 'blur'},
                    ]
                },
                formVisible: false,
                searchField: '',
                isModify: false,
                typeMap: ['photographers', 'retouchers', 'partners']
            }
        },
        computed: {
            formTitle () {
                return this.isModify ? '修改用户' : '添加用户'
            },
            filter () {
                return this.$route.params.filter
            },
        },
        mounted () {
            this.getList()
            document.addEventListener('keyup', (e) => {
                if (e.keyCode === '13') {
                    this.getList()
                }
            }, false)
        },
        methods: {
            async getList (currentPage = 1) {
                let postData = {
                    page: currentPage,
                }
                if (this.searchField) {
                    postData.name__contains = this.searchField
                }
                this.loading = true
                let res = await this.api.getUserList(this.filter, postData)
                if (res.success) {
                    this.list = res.data.results
                    this.total = res.data.count
                }
                this.loading = false
            },
            showAddForm () {
                this.isModify = false
                this.formVisible = true
            },
            hideAddForm () {
                this.formVisible = false
                this.$refs.form.resetFields()
                this.form.remark = ''
            },
            edit (idx) {
                this.isModify = true
                this.pointPersonId = this.list[idx].id
                this.form = JSON.parse(JSON.stringify(this.list[idx]))
                this.formVisible = true
            },
            submit () {
                this.$refs.form.validate(async (valid) => {
                    if (valid) {
                        let postData = this.form
                        if (this.isModify) {
                            postData.id = this.pointPersonId
                        }
                        let res = await this.api.createOrEditUser(this.isModify ? this.filter : this.typeMap[this.form.type], postData, this.isModify)
                        if (res.success) {
                            this.hideAddForm()
                            this.$Message.success(this.isModify ? '修改用户成功！': '创建用户成功！')
                            this.getList()
                        }
                    }
                })
            },
            changePage (pageIdx) {
                this.currentPage = pageIdx
                this.getList(pageIdx)
            },
            handleFilterChange (val) {
                this.getList()
            },
        },
        watch: {
            '$route.params': 'handleFilterChange'
        }
    };
</script>

<template>
  <div class="manage">
    <div class="statistic__search">
      <Input v-model="searchField" size="large" placeholder="请输入名字查询">
      <Button @click="getList(1)" slot="append" icon="ios-search"></Button>
      </Input>
    </div>
    <!-- 表格-->
    <Table style="margin-top: 20px;" border :context="self" :columns="columns" :data="list"></Table>
    <!-- 分页-->
    <Page :page-size="pageSize" :current="currentPage" :total="total" class-name="statistic__pager"
          @on-change="changePage"></Page>
    <!-- SPIN-->
    <Spin size="large" fix v-if="loading"></Spin>
    <!-- 添加用户-->
    <div class="statistic__add" layout="row center-left" @click="showAddForm">
      <Icon type="plus" style="margin-right: 5px;"></Icon>
      添加角色
    </div>
    <Modal
            v-model="formVisible"
            :title="formTitle"
            :mask-closable="false"
    >

      <Form class="statistic__form" ref="form" :model="form" :rules="rules" :label-width="100">

        <Form-item label="角色类型" v-if="!isModify">
          <Radio-group v-model="form.type" type="button">
            <Radio label="0">摄影师</Radio>
            <Radio label="1">修图师</Radio>
            <Radio label="2">合作方</Radio>
          </Radio-group>
        </Form-item>
        <Form-item prop="name" label="名字">
          <Input v-model="form.name" placeholder="请输入名字" icon="android-person"/>
        </Form-item>
        <Form-item prop="phone" label="手机号">
          <Input v-model="form.phone" placeholder="请输入手机号（将用作账号）" icon="ios-telephone"/>
        </Form-item>
        <!--<Form-item prop="password" label="密码">-->
          <!--<Input v-model="form.password" placeholder="请分配密码" icon="android-more-horizontal"/>-->
        <!--</Form-item>-->
        <Form-item prop="email" label="邮箱">
          <Input v-model="form.email" placeholder="请输入邮箱" icon="ios-email"/>
        </Form-item>
        <Form-item label="备注">
          <Input type="textarea" :rows="4" v-model="form.remark" placeholder="备注"/>
        </Form-item>

      </Form>
      <div slot="footer">
        <Button type="text" @click="hideAddForm">取消</Button>
        <Button type="primary" size="large" :loading="loading" @click="submit">确认</Button>
      </div>
    </Modal>
  </div>
</template>